package com.example.controller;

import com.example.entity.User;
import com.example.entity.Student;
import com.example.service.UserService;
import com.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/user")
public class RegisterController {

    @Autowired
    private UserService userService;

    @Autowired
    private StudentService studentService;

    @GetMapping("/register")
    public String showRegisterForm() {
        return "register";
    }

    @PostMapping("/register")
    public String register(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam String name,
            @RequestParam String email,
            @RequestParam String phone,
            @RequestParam String department) {

        // 创建用户
        User user = new User(username, password, "student");
        userService.saveUser(user);

        // 创建学生信息
        Student student = new Student(name, email, phone, department);
        student.setUser(user);
        studentService.saveStudent(student);

        return "redirect:/index.jsp?register=success";
    }
}